package com.rising.face.suanfa.threadprint3;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2021/2/7 19:28
 */
public class ThreadPrint3 {

    private volatile int currentThread = 0;
    private int threadNum;

    //打印总数
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private Lock lock = new ReentrantLock();
    private Condition[] conditions;

    public ThreadPrint3() {

    }

    public void print(Thread thread) {
        while (atomicInteger.get() <= 100) {
            int threadName = Integer.valueOf(thread.getName());
            lock.lock();
            try {
                while (currentThread != threadName) {
                    conditions[threadName].await();
                }
                if (atomicInteger.get() <= 100) {
                    System.out.println("thread" + threadName + ":" + atomicInteger.getAndIncrement());
                }

                //说明是最后一个线程
                if (currentThread == threadNum - 1) {
                    currentThread = 0;
                } else {
                    currentThread++;
                }
                conditions[currentThread].signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public void threadPrint(int threaNum) {
        this.threadNum = threaNum;
        conditions = new Condition[threaNum];
        for (int i = 0; i < conditions.length; i++) {
            conditions[i] = lock.newCondition();
        }

        for (int i = 0; i < threaNum; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    print(Thread.currentThread());
                }
            }, i + "").start();
        }
    }
}
